<template>
  <div class="comments-panel">
    <div class="avatar-wrap">
      <avatars  v-if="formState.nickname"  :avatar-name="formState.nickname"/>
      <div v-else class="default-avatar"></div>
    </div>
    <div class="editor-wrap">
      <a-form :model="formState"  :rules="rules"  ref="formRef">
        <a-row  type="flex" justify="space-between">
          <a-col :xs="24" :sm="24" :md="11" >
            <a-form-item has-feedback name="nickname">
              <a-input  v-model:value="formState.nickname" placeholder="您的昵称"   >
                <template #addonBefore>
                  <UserOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="11" >
            <a-form-item  name="email">
              <a-input   v-model:value="formState.email" placeholder="您的邮箱（可选）" allowClear >
                <template #addonBefore>
                  <MailOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row  type="flex" justify="space-between">
          <a-col :xs="24" :sm="24" :md="11" >
            <a-form-item name="homepage">
              <a-input  v-model:value="formState.homepage" placeholder="您的主页（可选）" allowClear  >
                <template #addonBefore>
                  <LinkOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="11" >
            <a-form-item name="git">
              <a-input  v-model:value="formState.git" placeholder="您的github（可选）" allowClear >
                <template #addonBefore>
                  <GithubOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <VMdWrap  @onChange="onChange" @onSubmit="onSubmit" :value="textarea" ref="child"/>
    </div>
    <div class="foot-tip" v-if="tips">
      <ExclamationCircleOutlined />温馨提示：网络不是法外之地，请谨言慎行！
      <i class="close-tip" @click="closeTip"> <CloseCircleOutlined /></i>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive,ref,toRefs,toRaw,onMounted} from "vue";
import { message } from 'ant-design-vue';
import avatars from "./avatars.vue";
import VMdWrap from '../../components/vue-markdown-editor.vue'
import {getStorage,setStorage} from '@/utils/config'
import { addComment } from  '@/utils/api'

let emit = defineEmits(['refresh'])

let formState = reactive({
  nickname:<string> '',
  email:<string> '',
  homepage: <string>'',
  git:<string>''
});
let child = ref()
const formRef = ref();
const textarea = ref('')
const onChange = (text:any,html:any)=>{
    textarea.value = text
}
const tips = ref(true)
const closeTip = ()=>{
  tips.value = false
  sessionStorage.setItem('tips','false')
}
// 提交内容
const onSubmit = (text:any)=>{
  formRef.value
      .validate()
      .then(() => {
        if (textarea.value){
          if (textarea.value.length>300){
            message.error('输入的内容太多啦，请保持在300字以内吧!',2.5)
          }else {
            setStorage('USER_INFO',toRaw(formState))
            addComm()
          }

        }else {
          console.log('内容为空')
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
}

const addComm = ()=>{
  let loading = true
  message
      .loading('数据正在生成..', 2.5)
      .then(
          () => {
            if(!loading){
              textarea.value = ''
              emit('refresh')
              message.success('评论成功', 2.5)
            }else {
              message.error('评论失败', 2.5)
            }
          },
          () => {
            message.error('评论失败', 2.5)
          },
      )

  addComment({
    ...toRaw(formState),
    content:textarea.value
  }).then(res=>{
    loading = false
    //刷新评论列表

  })
}

let checkAge = async (rule: any, value: any) => {
  if (value === '') {
    return Promise.reject('朋友，该怎么称呼您呢？');
  }else if (value.length>8) {
    return Promise.reject('达咩，请使用简短一点的昵称吧！');
  }else if(value=='admin'||value=='same'||value=='coco'){
    return Promise.reject('哦呜，你不可以使用这个昵称哟！');
  }
  return Promise.resolve();
}
let checkEamil = async (rule: any, value: any) => {
  if ( value) {
    let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    if (!reg.exec(value)){
      return Promise.reject('啊这，你的邮箱地址好像不正确!');
    }
  }
  return Promise.resolve();
}
let checkHtml = async (rule: any, value: any) => {
  if ( value) {
    let reg = /^(http(s)?:\/\/)?([0-9a-z-]{1,}.)?[0-9a-z-]{2,}.([0-9a-z-]{2,}.)?[a-z]{2,}$/i;
    if (!reg.exec(value)){
      return Promise.reject('请规范输入您的主页吧 ~  http(s)//xxx.xxx\'');
    }
  }
  return Promise.resolve();
}
let checkGit = async (rule: any, value: any) => {
  if ( value) {
    let reg = /^(http(s)?:\/\/([^\/]+?\/){2}|git@[^:]+:[^\/]+?\/).*?.git$/
    if (!reg.exec(value)){
      return Promise.reject('奇怪，和别人的怎么不一样：https://github.com/xxx/test.git');
    }
  }
  return Promise.resolve();
}
const rules = {
  nickname: [{ required: true, validator: checkAge, trigger: 'change' }],
  email: [{ required: true, validator: checkEamil, trigger: 'change' }],
  homepage: [{ required: true, validator: checkHtml, trigger: 'change' }],
  git: [{ required: true, validator: checkGit, trigger: 'change' }],
}

onMounted(() => {
  let user = getStorage('USER_INFO')
  if(user){
    for(let i in user){
      if (user[i]){
        formState[i] = user[i]
      }
    }

  }
  let tip = sessionStorage.getItem('tips')
  if (tip!=null){
    tips.value = false
  }

})

</script>
<style scoped>
.comments-panel{
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-wrap:wrap;
}
.foot-tip{
  width: 100%;
  height: 40px;
  line-height: 40px;
  color: #573A08;
  background: #FFFAF3;
  /*border: 1px solid #e3e9ed;*/
  margin-top: 20px;
  padding-left: 15px;
  letter-spacing: 2px;
  -webkit-box-shadow: 0px 0px 0px 1px #c9ba9b inset, 0px 0px 0px 0px rgba(0,0,0,0);
  box-shadow: 0px 0px 0px 1px #c9ba9b inset,0px 0px 0px 0px rgba(0,0,0,0);
  position: relative;
}
.foot-tip span{
  margin: 0 10px;
}
.close-tip{
  position: absolute;
  right: 15px;
  cursor: pointer;
  font-size: 18px;
  color: #efd8a7;
}
.close-tip:hover{
  color: #de4040;
  animation: close  1s  infinite;
  animation-iteration-count:1;
}
@keyframes close {

  from{
    transform: rotate(0deg);
  }
  to{
    transform: rotate(360deg);
  }
}
.avatar-wrap{
  width: 50px;
  height: 50px;
  border-radius: 4px;
  overflow: hidden;
  -webkit-box-flex: 0;
  flex: none;
  margin-right: 16px;
  border: 1px solid #ddd;
  padding: 3px;
}
.default-avatar{
  width: 100%;
  height: 100%;
  background: url("../../assets/img/avator.png") 50% no-repeat #ccc;;
  background-size: 30px;;
}
.editor-wrap{
  -webkit-box-flex: 1;
  flex: auto;
}
</style>